import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

packageName = "cn.lijin.entity;"    // 此处指定包路径，也就对应实体类中的package cn.lijin.entity;
typeMapping = [    // 此处指定对应的类型映射，如下：数据库中bigint对应生成java的Long，int|tinyint生成Integer...
                   (~/(?i)bigint/)                      : "Long",
                   (~/(?i)int|tinyint/)                 : "Integer",
                   (~/(?i)float|double|decimal|real/)   : "java.math.BigDecimal",
                   (~/(?i)date|datetime|timestamp/)     : "java.util.Date",
                   (~/(?i)time/)                        : "java.sql.Time",
                   (~/(?i)/)                            : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def fields = calcFields(table)
  new PrintWriter(new OutputStreamWriter(new FileOutputStream( new File(dir, className + ".java")), "utf-8")).withPrintWriter { out -> generate(out, className, fields) }
}

def generate(out, className, fields) {   // 从这里开始，拼实体类的具体逻辑代码
  out.println "package $packageName"
  out.println ""
  out.println "import lombok.Data;"     // 因为我使用了lombok插件，使用到了Data注解，所以在引包时加了这一行
  out.println "import java.io.Serializable;"
  out.println ""
  out.println "@Data"
  out.println "public class $className  implements Serializable {"
  out.println ""
  out.println genSerialID()
  out.println ""
  int i = 0
  fields.each() {   // 遍历字段，按下面的规则生成
    // 输出注释
    if (isNotEmpty(it.commoent)) {
      out.println "\t/**"
      out.println "\t * ${it.commoent}"
      out.println "\t */"
    }
    if (it.annos != "") out.println "  ${it.annos}"
    out.println "\tprivate ${it.type} ${it.name};"
    out.println ""
    i++
  }
  out.println ""
  out.println "}"
}

def calcFields(table) {
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDataType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                       name : javaName(col.getName(), false),
                       type : typeStr,
                       commoent: col.getComment(),
                       annos: ""]]
  }
}

def isNotEmpty(content) {
  return content != null && content.toString().trim().length() > 0
}

def javaName(str, capitalize) {
  def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
          .collect { Case.LOWER.apply(it).capitalize() }
          .join("")
          .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

//生成序列化的serialVersionUID
static String genSerialID() {
  return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;"
}